'use strict';
const { Service } = require('egg');
const Result = require('../util/result');
const GenTicketId = require('../util/genTicketId');
const CalculateAmount = require('../util/calculateAmount');

class TicketService extends Service {
  async list(query) {
    const info = await this.ctx.model.Ticket.findAll(query);
    if (!info) {
      this.logger.error('[订单列表查询] 订单列表为空');
      return Result.result(-1, '查询列表失败', info);
    }
    return Result.success(info);
  }

  async findByBuyerId(id, query) {
    if (!id) return Result.warn(-1, 'id不存在');
    const info = await this.ctx.model.Ticket.findAll({
      where: {
        buyer_id: id,
      },
      ...query,
    });
    if (!info) {
      this.logger.error(`[订单列表查询] 查询数据为空--buyer_id=${id}`);
      return Result.warn(-1, '未查询到数据');
    }
  }

  async create(data) {
    const { buyer_id, start_station, end_station, go_date, go_time, train_num, seat_num, seat_type } = data;
    const ticket_id = GenTicketId.geneteId();
    let start_index,
      end_index;
    const train_info = await this.ctx.service.train.findByTrainNum(train_num);
    const trainline_info = await this.ctx.service.trainline.findOne(train_info.id);
    trainline_info.forEach((item, index) => {
      if (item.station_name === start_station) {
        start_index = index;
      }
      if (item.station_name === end_station) {
        end_index = index;
      }
    });
    const count = end_index - start_index;
    const amount = CalculateAmount.calculate(train_info.train_type, count);
    const info = await this.ctx.model.Ticket
      .create({ ticket_id, buyer_id, start_station, end_station, go_date, go_time, train_num, seat_num, seat_type, amount });
    if (!info) {
      this.logger.error(`[创建订单]--订单创建失败 create info=${data}`);
      return Result.warn(-1, '创建失败');
    }
  }

  async findOne(id) {
    if (!id) {
      this.logger.error('[订单查询] id不存在');
      return Result.warn(-1, 'id不存在');
    }
    const info = await this.findById(id);
    if (!info) {
      this.logger.error('[订单查询] 订单不存在');
      return Result.warn(-1, '订单不存在');
    }
    return Result.success(info);
  }

  async update(id, data) {

    const info = await this.findById(id);
    if (!info) {
      this.logger.info(`[订单查询]  订单不存在 id=${id}`);
      return Result.warn(-1, '订单不存在');
    }
    const result = await this.ctx.model.Ticket.update({
      where: { ticket_id: id },
    }, { ...data });
    if (result[0] === 0) {
      this.logger.error(`[订单更新] 订单更新失败，data=${data}`);
      return Result.warn(-1, '订单更新失败');
    }
    const res = await this.findById(id);
    return Result.success(res);
  }

  async destroy(id) {
    if (!id) {
      this.logger.error('[订单查询]  id不存在');
      return Result.warn(-1, 'id不存在');
    }
    const info = await this.findById(id);
    if (!info) {
      this.logger.info(`[订单查询] 查询失败  id=${id},info=${info}`);
      return Result.warn(-1, '未查询到订单');
    }
    await this.ctx.model.Ticket.destroy({
      where: {
        ticket_id: id,
      },
    });
    return Result.noDataSuccess();
  }

  async findById(id) {
    return await this.ctx.model.Ticket.findByPk(id);
  }

  async finishOrder(id) {
    const res = await this.ctx.model.Ticket.update({
      where: {
        ticket_id: id,
      },
    }, {
      ticket_status: 1,
    });
    if (res[0] === 0) {
      this.logger.error(`[订单更新] ticket_id=${id}`);
      return Result.warn(-1, '订单更新失败');
    }

    const data = await this.findById(id);

    return Result.success(data);
  }
}

module.exports = TicketService;
